package org.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.chen.domain.entity.AvatarSyncRecord;
import org.chen.domain.entity.UserVideoConfig;
import org.chen.domain.entity.VideoAvatar;
import org.chen.client.HeyGenClient;
import org.chen.mapper.AvatarMapper;
import org.chen.mapper.AvatarSyncRecordMapper;
import org.chen.mapper.UserVideoConfigMapper;
import org.chen.response.Avatar;
import org.chen.response.KeyAvatarGroupResponse;
import org.chen.response.KeyAvatarResponse;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class KeyAvatarService {
    private final AvatarMapper videoAvatarMapper;
    private final UserVideoConfigMapper userVideoConfigMapper;
    private final HeyGenClient heygenClient;
    private final AvatarSyncRecordMapper syncRecordMapper;

    // 获取最后一次同步信息
    public AvatarSyncRecord getLastSyncInfo() {
        return syncRecordMapper.selectOne(
                new QueryWrapper<AvatarSyncRecord>()
                        .orderByDesc("sync_time")
                        .last("LIMIT 1")
        );
    }

    // 保存同步记录
    private void saveSyncRecord(AvatarSyncRecord record) {
        syncRecordMapper.insert(record);
    }

    public List<UserVideoConfig> listConfigs() {
        return userVideoConfigMapper.selectList(
                new QueryWrapper<UserVideoConfig>()
                        .orderByDesc("create_time")
        );
    }

    public void saveConfig(UserVideoConfig config) {
        if (config.getId() == null) {
            // 新增配置
            if (config.getIsDefault() != null && config.getIsDefault()) {
                // 如果是默认配置，先将该avatar_id的其他默认配置取消
                UserVideoConfig existingDefault = userVideoConfigMapper.selectOne(
                        new QueryWrapper<UserVideoConfig>()
                                .eq("avatar_id", config.getAvatarId())
                                .eq("is_default", true)
                );
                if (existingDefault != null) {
                    existingDefault.setIsDefault(false);
                    userVideoConfigMapper.updateById(existingDefault);
                }
            }
            userVideoConfigMapper.insert(config);
        } else {
            // 更新配置
            UserVideoConfig existConfig = userVideoConfigMapper.selectById(config.getId());
            if (existConfig != null) {
                if (Boolean.TRUE.equals(config.getIsDefault())) {
                    // 如果设置为默认，先将其他默认取消
                    userVideoConfigMapper.update(null,
                            new UpdateWrapper<UserVideoConfig>()
                                    .eq("avatar_id", config.getAvatarId())
                                    .eq("is_default", true)
                                    .set("is_default", false)
                    );
                }
                userVideoConfigMapper.updateById(config);
            } else {
                throw new RuntimeException("配置不存在");
            }
        }
    }

    public String syncAvatarsFromHeygen() {
        AvatarSyncRecord record = new AvatarSyncRecord();
        record.setSyncTime(LocalDateTime.now());

        int added = 0;
        int updated = 0;
        int failed = 0;
        int deleted = 0;

        try {
            // 1. 获取所有角色组
            KeyAvatarGroupResponse keyAvatarGroup = heygenClient.getKeyAvatarGroup();
            List<org.chen.response.AvatarGroup> groups = keyAvatarGroup.getData().getAvatar_group_list();

            // 删除自动生成的配置
            userVideoConfigMapper.delete(new QueryWrapper<UserVideoConfig>().eq("is_auto", true));

            // 2. 遍历角色组获取具体角色
            for (org.chen.response.AvatarGroup group : groups) {
                KeyAvatarResponse keyAvatar = heygenClient.getKeyAvatar(group.getId());
                List<Avatar> avatars = keyAvatar.getData().getAvatar_list();

                for (Avatar avatar : avatars) {
                    if (avatar.getMotion_preview_url() == null || avatar.getMotion_preview_url().isEmpty()) {
//                        log.info("Skipping avatar {} because motion_preview_url is empty", avatar.getId());
                        continue;
                    }

                   try {
                       // 3. 检查是否存在
                       VideoAvatar existingAvatar = videoAvatarMapper.selectOne(
                               new QueryWrapper<VideoAvatar>()
                                       .eq("avatar_id", avatar.getId())
                       );

                       // 4. 保存或更新到VideoAvatar表
                       VideoAvatar videoAvatar = new VideoAvatar();
                       videoAvatar.setAvatarId(avatar.getId());
                       videoAvatar.setAvatarName(avatar.getName());
                       videoAvatar.setPreviewImageUrl(avatar.getImage_url());
                       videoAvatar.setPreviewVideoUrl(avatar.getMotion_preview_url());
                       videoAvatar.setGender("unknown");
                       videoAvatar.setIsPublic(false);

                       if (existingAvatar != null) {
                           videoAvatar.setId(existingAvatar.getId());
                           videoAvatarMapper.updateById(videoAvatar);
                           updated++;
                       } else {
                           videoAvatarMapper.insert(videoAvatar);
                           added++;
                       }

                       // 5. 创建自动配置
                       createDefaultConfig(avatar);
                   } catch (Exception e) {
                       failed++;
                       log.error("Failed to sync avatar: {}", avatar.getId(), e);
                   }
                }
            }

            record.setStatus("SUCCESS");
            record.setAddedCount(added);
            record.setUpdatedCount(updated);
            record.setFailedCount(failed);

        } catch (Exception e) {
            record.setStatus("FAILED");
            record.setErrorMessage(e.getMessage());
            throw e;
        } finally {
            saveSyncRecord(record);
        }
        return String.format("同步完成：新增 %d 个，更新 %d 个，删除 %d 个，失败 %d 个",
                added, updated, deleted, failed);
    }

    private void createDefaultConfig(Avatar avatar) {
        UserVideoConfig config = new UserVideoConfig();
        config.setName(avatar.getName() + "-默认配置");
        config.setAvatarId(avatar.getId());
        config.setBackgroundColor("#f6f6fc");
        config.setWidth(1080);
        config.setHeight(1920);
        config.setIsCaption(false);
        config.setIsAuto(true);
        config.setIsDefault(true);
        userVideoConfigMapper.insert(config);
    }
}
